package com.hthy.futures.ui.fragment;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hthy.futures.R;
import com.hthy.futures.api.ST_QuoteApi;
import com.hthy.futures.base.BaseFragment;
import com.hthy.futures.bean.Count;
import com.hthy.futures.inter.NewOrderNeedRefresh;
import com.hthy.futures.ui.activity.MainActivity;
import com.hthy.futures.utils.Contant;
import com.hthy.futures.utils.LogUtils;
import com.vilyever.socketclient.SocketClient;
import com.wordplat.ikvstockchart.InteractiveKLineLayout;
import com.wordplat.ikvstockchart.KLineHandler;
import com.wordplat.ikvstockchart.entry.Entry;
import com.wordplat.ikvstockchart.entry.EntrySet;
import com.wordplat.ikvstockchart.entry.SizeColor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import de.greenrobot.event.EventBus;

import static com.hthy.futures.api.ST_QuoteApi.K_REQUEST_NUM;

/**
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/4/24
 */

public class KLineFragment extends BaseFragment {
    @Bind(R.id.title_lay)
    LinearLayout title_lay;
    @Bind(R.id.horizontalScrollView)
    HorizontalScrollView mHorizontalScrollView;
    @Bind(R.id.MA_Text)
    TextView mMA_text;


    Context mContxt;

    @Bind(R.id.kLineLayout0)
    InteractiveKLineLayout mKLineLayout0;
    @Bind(R.id.kLineLayout1)
    InteractiveKLineLayout mKLineLayout1;
    @Bind(R.id.kLineLayout2)
    InteractiveKLineLayout mKLineLayout2;
    @Bind(R.id.kLineLayout3)
    InteractiveKLineLayout mKLineLayout3;
    @Bind(R.id.kLineLayout4)
    InteractiveKLineLayout mKLineLayout4;
    @Bind(R.id.kLineLayout5)
    InteractiveKLineLayout mKLineLayout5;
    @Bind(R.id.kLineLayout6)
    InteractiveKLineLayout mKLineLayout6;
    @Bind(R.id.kLineLayout7)
    InteractiveKLineLayout mKLineLayout7;
    @Bind(R.id.kLineLayout8)
    InteractiveKLineLayout mKLineLayout8;
    @Bind(R.id.kLineLayout9)
    InteractiveKLineLayout mKLineLayout9;
    @Bind(R.id.kLineLayout10)
    InteractiveKLineLayout mKLineLayout10;
    private List<InteractiveKLineLayout> kLineLayouts = new ArrayList<>();
    private List<Count> mCounts = new ArrayList<>();
    private int radioSelectIndex;

    private Resources res;
    private String kChartTimeInterval;                       //图表数据间隔
    private RadioGroup myRadioGroup;
    private List<Map<String, Object>> titleList = new ArrayList<Map<String, Object>>();
    private String mSs_product_code;
    private SocketClient mSocketClient;

    //定时器
    Timer timer1 = null;  //刷新定时器
    // 1000 等于 1s
    public final int one_minute = 2000;
    private final int dataRefreshTime_one_minute = one_minute;                         //1分钟
    private final int dataRefreshTime_five_minute = one_minute * 5;                         //5分钟
    private final int dataRefreshTime_ten_minute = one_minute * 10;                       // 10分钟


    private EntrySet entrySet;

    Handler handlerOfTrans = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                LogUtils.e("kline", "有新数据");
                indexMarketChart(Integer.parseInt(kChartTimeInterval), 0, mSs_product_code);
            }
            super.handleMessage(msg);
        }
    };


    private ImageView left_loading_image;
    private int refresh_count = 0;
    List<Entry> mSaveListEntry = new ArrayList<>();

    /**
     * 处理K线逻辑
     *
     * @param
     */
    public void setEntrySet(EntrySet entrySet) {
        InteractiveKLineLayout kLineLayout = kLineLayouts.get(radioSelectIndex - 1);
        int refresh_count = mCounts.get(radioSelectIndex - 1).refresh_count;
        List<Entry> mSaveListEntry = mCounts.get(radioSelectIndex - 1).mSaveListEntry;

        EntrySet mEntrySet = entrySet;

        if (refresh_count == 0) {
            if (mSaveListEntry.size() > 0) {
                mSaveListEntry.clear();
            }
        }
        List<Entry> adddList = mEntrySet.getEntryList();
        if (adddList.size() < K_REQUEST_NUM) {
            kLineLayout.getKLineView().setEnableLeftRefresh(false);
        }

        LogUtils.e("bbb", "每次增加的数量" + adddList.size());
        if (refresh_count > 0) {
            mSaveListEntry.addAll(0, adddList);
            List<Entry> entryList = kLineLayout.getKLineView().getRender().getEntrySet().getEntryList();
            if (entryList.size() > 0) {
                entryList.clear();
            }
            mCounts.get(radioSelectIndex - 1).mSaveListEntry = mSaveListEntry;
            entryList.addAll(mSaveListEntry);
            LogUtils.e("bbb", "第" + (radioSelectIndex - 1) + "页索引:" + refresh_count + ", 数据源size：" + entryList.size());
            kLineLayout.getKLineView().getRender().getEntrySet().entries = entryList;
            kLineLayout.getKLineView().notifyDataSetChanged();
            // kLineLayout0.getKLineView().refreshComplete(adddList.size() > 0);
        } else {
            mSaveListEntry.addAll(mEntrySet.getEntryList());  // 之所以要加要跟后面就行合并
            LogUtils.e("bbb", "第一页:" + refresh_count + ", 数据源size：" + mCounts.get(radioSelectIndex - 1).mSaveListEntry.size());
            kLineLayout.getKLineView().setEntrySet(mEntrySet);
            kLineLayout.getKLineView().notifyDataSetChanged();
        }

        // 通知外部显示页面
        EventBus.getDefault().post(new NewOrderNeedRefresh(true));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frg_kline;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        initInteractiveKLayout();
        mContxt = getActivity();
        res = mContxt.getResources();
        initGroup(root);

    }

    /**
     * 初始化 InteractiveKLineLayout 相关的属性
     */
    private void initInteractiveKLayout() {
        kLineLayouts.clear();

        kLineLayouts.add(mKLineLayout0);
        kLineLayouts.add(mKLineLayout1);
        kLineLayouts.add(mKLineLayout2);
        kLineLayouts.add(mKLineLayout3);
        kLineLayouts.add(mKLineLayout4);
        kLineLayouts.add(mKLineLayout5);
        kLineLayouts.add(mKLineLayout6);
        kLineLayouts.add(mKLineLayout7);
        kLineLayouts.add(mKLineLayout8);
        kLineLayouts.add(mKLineLayout9);
        kLineLayouts.add(mKLineLayout10);

        for (int i = 0; i < kLineLayouts.size(); i++) {
            // 都禁止向右加载
            final InteractiveKLineLayout kLineLayout = kLineLayouts.get(i);
            kLineLayout.getKLineView().setEnableRightRefresh(false);
            mCounts.add(new Count());
            final int postion = i;
            kLineLayout.setKLineHandler(new KLineHandler() {
                @Override
                public void onLeftRefresh() {
                    int refresh_count = mCounts.get(postion).refresh_count;
                    refresh_count += 1;
                    mCounts.get(postion).refresh_count = refresh_count;
                    // 当有执行向左刷新操作，说明不是从零开始，
                    // 去请求下一段数据
                    if (refresh_count > 0) {
                        indexMarketChart(Integer.parseInt(kChartTimeInterval), K_REQUEST_NUM * refresh_count, mSs_product_code);
                    }
                }

                @Override
                public void onRightRefresh() {

                }

                @Override
                public void onSingleTap(MotionEvent e, float x, float y) {

                }

                @Override
                public void onDoubleTap(MotionEvent e, float x, float y) {

                }

                @Override
                public void onHighlight(Entry entry, int entryIndex, float x, float y) {
                    mMA_text.setVisibility(View.VISIBLE);
                    final SizeColor sizeColor = kLineLayout.getKLineView().getRender().getSizeColor();
                    String maString = String.format(getResources().getString(R.string.ma_highlight),
                            entry.getMa5(),
                            entry.getMa10(),
                            entry.getMa20());
                    mMA_text.setText(getSpannableString(maString,
                            sizeColor.getMa5Color(),
                            sizeColor.getMa10Color(),
                            sizeColor.getMa20Color()));
                }

                @Override
                public void onCancelHighlight() {
                    mMA_text.setVisibility(View.GONE);
                }
            });
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void initGroup(View contentView) {
        initGroupTab();

        title_lay = (LinearLayout) contentView.findViewById(R.id.title_lay);
        myRadioGroup = new RadioGroup(mContxt);
        myRadioGroup.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        myRadioGroup.setOrientation(LinearLayout.HORIZONTAL);
        title_lay.addView(myRadioGroup);
        for (int i = 0; i < titleList.size(); i++) {
            Map<String, Object> map1 = titleList.get(i);
            RadioButton radio = new RadioButton(mContxt);
            radio.setButtonDrawable(R.color.kViewztblack);
            LinearLayout.LayoutParams l = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT,
                    Gravity.CENTER);
            radio.setLayoutParams(l);
            radio.setGravity(Gravity.CENTER);
            radio.setPadding(20, 20, 20, 20);
            // radio.setPadding(left, top, right, bottom)
            radio.setId(1 + i);
            radio.setText(map1.get(Contant.title) + "");
            if (i == 0) {
                radio.setTextColor(getResources().getColor(R.color.colorPrimary));
                radio.setChecked(true);
                radio.setBackground(getResources().getDrawable(R.drawable.bg_bottom));
            } else {
                radio.setTextColor(getResources().getColor(R.color.kViewztblack));
                radio.setChecked(false);
                radio.setBackground(null);
            }

            radio.setTag(map1);
            myRadioGroup.addView(radio);

        }
        // 默认开启一分钟定时器
        //startTimer(one_minute);
        myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                radioSelectIndex = group.getCheckedRadioButtonId();
                // 根据ID获取RadioButton的实例
                RadioButton rb = (RadioButton) getActivity().findViewById(radioSelectIndex);
                for (int i = 0; i < group.getChildCount(); i++) {
                    RadioButton vradio = (RadioButton) group.getChildAt(i);
                    vradio.setGravity(Gravity.CENTER);
                    vradio.setPadding(20, 20, 20, 20);
                    if (rb.getId() == vradio.getId()) {
                        vradio.setTextColor(getResources().getColor(R.color.colorPrimary));
                        vradio.setChecked(true);
                        vradio.setBackground(getResources().getDrawable(R.drawable.bg_bottom));
                        MainActivity.requestType = Integer.parseInt(titleList.get(checkedId - 1).get(Contant.id) + "");
                    } else {
                        //stopTimer();  // 关闭定时器
                        vradio.setTextColor(getResources().getColor(R.color.kViewztblack));
                        vradio.setChecked(false);
                        vradio.setBackground(null);
                    }
                }
                int timeer = (int) titleList.get(checkedId - 1).get(Contant.timmer);
                //startTimer(timeer);
                // refresh_count = 0;
                kChartTimeInterval = titleList.get(checkedId - 1).get(Contant.time) + "";

                if (((Boolean) titleList.get(checkedId - 1).get(Contant.isCanRequest)) == false) {

                } else {
                    indexMarketChart(Integer.parseInt(kChartTimeInterval), 0, mSs_product_code);
                }
                titleList.get(checkedId - 1).put(Contant.isCanRequest, false);


                for (InteractiveKLineLayout kLineLayout : kLineLayouts) {
                    kLineLayout.setVisibility(View.GONE);
                }
                kLineLayouts.get(radioSelectIndex - 1).setVisibility(View.VISIBLE);
            }
        });
        //kLineLayout0.getKLineView().setEnableLeftRefresh(true);
        for (InteractiveKLineLayout kLineLayout : kLineLayouts) {
            kLineLayout.setVisibility(View.GONE);
        }
        kLineLayouts.get(0).setVisibility(View.VISIBLE);
        radioSelectIndex = 1;
    }

    /**
     * 请求k线数据
     *
     * @param kChartTimeInterval
     * @param ss_product_code
     */
    private void indexMarketChart(int kChartTimeInterval, int dataIndex, String ss_product_code) {
        byte[] histotryData = ST_QuoteApi.getHistotryData(kChartTimeInterval, dataIndex, ss_product_code);
        mSocketClient.sendData(histotryData);
    }

    /**
     * @param ss_product_code
     * @param socketClient
     */
    public void setPriceInfo(String ss_product_code, SocketClient socketClient) {
        this.mSs_product_code = ss_product_code;
        this.mSocketClient = socketClient;

        // 默认是一分钟的线的数据
        //this.mGoodsName.setText(ss_product_code);
        kChartTimeInterval = "1";
        indexMarketChart(1, 0, ss_product_code);
    }

    /**
     * init radiotab 数据
     */
    private void initGroupTab() {
        Map<String, Object> map = new HashMap<String, Object>();
        map = new HashMap<String, Object>();
        map.put(Contant.id, "0");
        map.put(Contant.title, res.getString(R.string.one_min));
        map.put(Contant.time, 1 + "");
        map.put(Contant.isCanRequest, false);
        map.put(Contant.timmer, dataRefreshTime_one_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "1");
        map.put(Contant.title, res.getString(R.string.five_min));
        map.put(Contant.time, 5 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "2");
        map.put(Contant.title, res.getString(R.string.ten_min));
        map.put(Contant.time, 10 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "3");
        map.put(Contant.title, res.getString(R.string.fifteen_min));
        map.put(Contant.time, 15 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "4");
        map.put(Contant.title, res.getString(R.string.thirty_min));
        map.put(Contant.time, 30 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "5");
        map.put(Contant.title, res.getString(R.string.one_hour));
        map.put(Contant.time, 60 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "6");
        map.put(Contant.title, res.getString(R.string.two_hour));
        map.put(Contant.time, 62 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "7");
        map.put(Contant.title, res.getString(R.string.four_hour));
        map.put(Contant.time, 64 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "8");
        map.put(Contant.title, res.getString(R.string.one_day));
        map.put(Contant.time, 101 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "9");
        map.put(Contant.title, res.getString(R.string.one_week));
        map.put(Contant.time, 102 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
        map = new HashMap<String, Object>();
        map.put(Contant.id, "10");
        map.put(Contant.title, res.getString(R.string.one_month));
        map.put(Contant.time, 103 + "");
        map.put(Contant.isCanRequest, true);
        map.put(Contant.timmer, dataRefreshTime_five_minute);  // 定时器
        titleList.add(map);
    }

    /**
     * 启动定时器
     */
    public void startTimer(int timmer) {
        if (timer1 == null) {
            Log.i("KD_startTimer", "KD_startTimer+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            timer1 = new Timer();
            TransTimerTask task1 = new TransTimerTask(handlerOfTrans, 1);
            timer1.schedule(task1, 0, timmer);
        }
    }

    /**
     * 停止定时器
     */
    public void stopTimer() {
        if (timer1 != null) {
            Log.i("KD_stoptimer", "KD_stoptimer+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            timer1.cancel();
            timer1 = null;
        }
    }



    /**
     * 定时器任务
     */
    class TransTimerTask extends TimerTask {
        private int code;
        private Handler mHandler;

        public TransTimerTask() {

        }

        public TransTimerTask(Handler handler, int code) {
            this.mHandler = handler;
            this.code = code;
        }

        @Override
        public void run() {
            // 需要做的事:发送消息
            Message message = new Message();
            message.what = code;
            this.mHandler.sendMessage(message);
        }
    }


    private SpannableString getSpannableString(String str, int partColor0, int partColor1, int partColor2) {
        String[] splitString = str.split("[●]");
        SpannableString spanString = new SpannableString(str);

        int pos0 = splitString[0].length();
        int pos1 = pos0 + splitString[1].length() + 1;
        int pos2 = pos1 + splitString[2].length() + 1;
        int end = str.length();

        spanString.setSpan(new ForegroundColorSpan(partColor0),
                pos0, pos1, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        spanString.setSpan(new ForegroundColorSpan(partColor1),
                pos1, pos2, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        spanString.setSpan(new ForegroundColorSpan(partColor2),
                pos2, end, SpannableString.SPAN_EXCLUSIVE_INCLUSIVE);

        return spanString;
    }
}
